package logic

import (
	"context"
	"errors"
	"math/rand"
	"time"
	"user-auth/models/cache"
	"user-auth/userrpc/internal/svc"
	"user-auth/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *userrpc.SendSmsRequest) (*userrpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line

	code := rand.Intn(9000) + 1000

	i, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Int()
	cache.Rdb.Set(l.ctx, "sendSms"+in.Mobile, i, time.Minute*1)
	//sms, err := pkg.SendSms(in.Mobile, strconv.Itoa(code))
	//if err != nil {
	//	return nil, err
	//}
	//
	//if sms.Code == 2 {
	//	return nil, errors.New("手机号格式错误")
	//}

	cache.Rdb.Set(l.ctx, "sendSms"+in.Mobile, code, time.Minute*3)
	if i >= 1 {
		cache.Rdb.Incr(l.ctx, "sendSms"+in.Mobile)
		return nil, errors.New("每分钟仅允许发送1次短信验证码")
	}

	return &userrpc.SendSmsResponse{}, nil
}
